package com.thinkfit.jy.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.common.lib.bean.ApplicationBean;
import com.common.lib.bean.SportInfoBean;
import com.common.lib.bean.UserBean;
import com.common.lib.bean.VersionBean;
import com.common.lib.constant.Constants;
import com.common.lib.constant.EventBusEvent;
import com.common.lib.fragment.BaseFragment;
import com.common.lib.manager.DataManager;
import com.common.lib.network.HttpListener;
import com.common.lib.network.HttpMethods;
import com.common.lib.network.HttpObserver;
import com.common.lib.network.OkHttpManager;
import com.common.lib.utils.BaseUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.thinkfit.jy.BuildConfig;
import com.thinkfit.jy.R;
import com.thinkfit.jy.activity.ApplicationActivity;
import com.thinkfit.jy.activity.FreeMovementNewActivity;
import com.thinkfit.jy.activity.LoginActivity;
import com.thinkfit.jy.activity.ProceduralTrainingActivity;
import com.thinkfit.jy.activity.UserProfileActivity;
import com.thinkfit.jy.activity.VideoActivity;
import com.thinkfit.jy.adapter.ApplicationAdapter;
import com.thinkfit.jy.adapter.DownloadAdapter;
import com.thinkfit.jy.contract.ApplicationContract;
import com.thinkfit.jy.dialog.HintPopupWindow;
import com.thinkfit.jy.presenter.ApplicationPresenter;
import com.thinkfit.jy.serialport.SerialPortManager;
import com.thinkfit.jy.utils.ApkListViewUtils;
import com.thinkfit.jy.utils.BluetoothOrder;
import com.thinkfit.jy.utils.DeviceTypeUtils;
import com.thinkfit.jy.utils.DialogCloseApkViewUtils;
import com.thinkfit.jy.utils.EquipmentInfoUtils;
import com.thinkfit.jy.utils.ImageLoadUtils;
import com.thinkfit.jy.utils.MotionDataUtils;
import com.thinkfit.jy.utils.RunningAppUtils;
import com.thinkfit.jy.utils.SetTargetViewUtils;
import com.thinkfit.jy.utils.ShowSpeedViewUtils;
import com.thinkfit.jy.utils.SportsStatusBarViewUtils;
import com.thinkfit.jy.utils.ThemeUtils;
import com.thinkfit.jy.utils.Utils;
import com.thinkfit.jy.view.SpaceItemDecoration;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class HomeSceneryFragment extends BaseFragment<ApplicationContract.Presenter> implements ApplicationContract.View {

    boolean isFirst = true;
    ImageView ivUserHead,ivDevice;
    TextView tvUserName,tvSetGoal;
    ConstraintLayout clSportInfo,clMain;
    CardView cvPrograms,cvImmersive,cvVideoCourse,cvAudioCourse,cvApp;
    ApplicationAdapter appAdapter;
    ArrayList<ImageView> ivs = new ArrayList<>();
    ArrayList<ImageView> ivMores = new ArrayList<>();
    ArrayList<TextView> tvs = new ArrayList<>();
    SpaceItemDecoration decoration;
    ArrayList<ImageView> imageViewList;
    int type = 0;
    int num = 0;

    static HomeSceneryFragment homeDWFragment;

    public static HomeSceneryFragment getInstance(){
        if(homeDWFragment == null){
            homeDWFragment = new HomeSceneryFragment();
        }
        return homeDWFragment;
    }

    @NonNull
    @Override
    protected ApplicationContract.Presenter onCreatePresenter() {
        return new ApplicationPresenter(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_scenery;
    }

    @Override
    protected void initView(@NonNull View view, @Nullable Bundle savedInstanceState) {
        setViewsOnClickListener(R.id.cl_sport_info,R.id.cl_user_login,R.id.tv_set_goal,
                R.id.cv_programs,R.id.cv_immersive,R.id.cv_video_course,R.id.cv_audio_course,R.id.cv_app);
        tvUserName = view.findViewById(R.id.tv_user_name);
        ivUserHead = view.findViewById(R.id.iv_user_head);
        ivDevice = view.findViewById(R.id.iv_device);
        clSportInfo = view.findViewById(R.id.cl_sport_info);
        clMain = view.findViewById(R.id.cl_main);
        tvSetGoal = view.findViewById(R.id.tv_set_goal);
        cvPrograms = view.findViewById(R.id.cv_programs);
        cvImmersive = view.findViewById(R.id.cv_immersive);
        cvVideoCourse = view.findViewById(R.id.cv_video_course);
        cvAudioCourse = view.findViewById(R.id.cv_audio_course);
        cvApp = view.findViewById(R.id.cv_app);
        UserBean myInfo = DataManager.Companion.getInstance().getMyInfo();
        if(myInfo != null){
            tvUserName.setText(getString(R.string.app_main_user_name,myInfo.getNickname()));
            BaseUtils.StaticParams.loadImage(getContext(), R.drawable.app_not_login, myInfo.getHeadimg(),ivUserHead);
        }else {
            tvUserName.setText(getString(R.string.app_main_user_name,"游客"));
            ivUserHead.setImageResource( R.drawable.app_not_login);
//            BaseUtils.StaticParams.loadImage(getContext(), R.drawable.app_not_login, myInfo.getHeadimg(),ivUserHead);
        }
        String homeApk = DataManager.Companion.getInstance().getHomeApk();
        if(!TextUtils.isEmpty(homeApk)){
            Gson gson = new Gson();
            Type type1 = new TypeToken<List<ApplicationBean>>() {
            }.getType();
            datas = gson.fromJson(homeApk, type1);
            imageViewList = getImageViewList(view);
            for (int i=0;i<imageViewList.size();i++){
                ImageLoadUtils.getInstance(getContext()).setImageUtlRadius(imageViewList.get(i),datas.get(i).getIcon(),0,4);
            }
//            initApplication(mRecyclerView,datas);
        }

    }

    public ArrayList<ImageView> getImageViewList(View view){
        ArrayList<ImageView> list = new ArrayList<>();
        list.add(view.findViewById(R.id.iv_1));
        list.add(view.findViewById(R.id.iv_2));
        list.add(view.findViewById(R.id.iv_3));
        list.add(view.findViewById(R.id.iv_4));
        return list;
    }

    private void initApplication(RecyclerView recyclerView, ArrayList<ApplicationBean> list) {
        if(decoration != null){
            recyclerView.removeItemDecoration(decoration);
            decoration = null;
        }
        GridLayoutManager layoutManager = new GridLayoutManager(getContext(),3);
        recyclerView.setLayoutManager(layoutManager);
        int screenWidth = BaseUtils.StaticParams.dp2px(getActivity(),400) - BaseUtils.StaticParams.dp2px(getActivity(),15)*2;// 23  recycleView 左右缩进距离
        int totalSpace=(screenWidth- BaseUtils.StaticParams.dp2px(getActivity(),100)*3);//  55 item宽度
        System.out.println("ddddddddddddddddddddddd  screenWidth : "+screenWidth+"  totalSpace : "+totalSpace);
        decoration = new SpaceItemDecoration(totalSpace,getActivity(),3);
        recyclerView.addItemDecoration(decoration);
        appAdapter = new ApplicationAdapter(getActivity(),ApplicationAdapter.HOME);
        appAdapter.addChildClickViewIds(R.id.ivUninstall);
        appAdapter.addChildClickViewIds(R.id.ll_more);
        appAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                switch (view.getId()) {
                    case R.id.ivUninstall:
                        Intent intent2 = new Intent(Intent.ACTION_DELETE);
                        intent2.setData(Uri.parse("package:" + appAdapter.getItem(position).getAppid()));
                        intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent2);
                        break;
                    case R.id.ll_more:
                        openActivity(ApplicationActivity.class);
                        break;
                }
            }
        });
        appAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                ApplicationBean bean = appAdapter.getItem(position);
//                    mFloatingView.setImageUrl(bean.getIcon());
//                    mFloatingView.show();

                if (bean.getInstallStatus() == 1) {
                    bean.setInstallStatus(0);
                }
                if (bean.getInstallStatus() != 2) {
                    switch (bean.getDownloadStatus()) {
                        case 0:
                        case 3:
                            bean.setProgress(0);
                            bean.setDownloadStatus(1);
                            appAdapter.notifyDataSetChanged();
                            OkHttpManager.Companion.getInstance().downloadApplication(bean);
                            break;
                        case 2:
                            if (bean.getDownloadFile() != null && bean.getDownloadFile().exists()) {
                                bean.setInstallStatus(1);
                                installApk(bean.getDownloadFile());
                            } else {
                                bean.setProgress(0);
                                bean.setDownloadStatus(1);
                                appAdapter.notifyDataSetChanged();
                                OkHttpManager.Companion.getInstance().downloadApplication(bean);
                            }
                            break;
                    }
                } else {
                    RunningAppUtils.getInstance().init(getContext());
                    ArrayList<ApplicationBean> currentRunningApp = RunningAppUtils.getInstance().getCurrentRunningApp();
                    boolean isOpen = RunningAppUtils.getInstance().isOpen(bean.getAppid());
                    System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   isOpen : "+isOpen);
                    if(!isOpen){//是否已经打开
                        if(currentRunningApp.size()>=3){
                            DialogCloseApkViewUtils.getInstance().initView(getContext(),bean.getAppid());
                        }else {
                            PackageManager packageManager = getContext().getPackageManager();
                            Intent intent = packageManager.getLaunchIntentForPackage(bean.getAppid());
                            if (intent != null) {
                                startActivity(intent);
                            }
                        }
                    }else {
                        PackageManager packageManager = getContext().getPackageManager();
                        Intent intent = packageManager.getLaunchIntentForPackage(bean.getAppid());
                        if (intent != null) {
                            startActivity(intent);
                        }
                    }
                }
            }
        });
        appAdapter.onAttachedToRecyclerView(recyclerView);
        recyclerView.setAdapter(appAdapter);
        appAdapter.setNewInstance(list);
    }

    public void setInfo(String kcal,String distance,String time){
        if(MotionDataUtils.getInstance().isRun()){
            clSportInfo.setVisibility(View.VISIBLE);
//            tvKcal.setText(kcal);
            setText(R.id.tv_kcal,kcal);
            setText(R.id.tv_distance,distance);
            setText(R.id.tv_sports_time,time);
        }
    }

    public void setDeviceImg(){
        switch (MotionDataUtils.mCurrentDeviceType){
            case DeviceTypeUtils.TREADMILL:
                ivDevice.setImageResource(R.drawable.img_main_treadmill);
                break;
            case DeviceTypeUtils.ELLIPTICAL_MACHINE:
                ivDevice.setImageResource(R.drawable.img_main_elliptical_machine);
                break;
            case DeviceTypeUtils.SPINNING:
                ivDevice.setImageResource(R.drawable.img_main_spinning);
                break;
            case DeviceTypeUtils.ROWING_MACHINE:
                ivDevice.setImageResource(R.drawable.img_main_rowing_machine);
                break;

        }
    }

    public void sportsInfoGone(){
        setText(R.id.tv_kcal,0);
        setText(R.id.tv_distance,0);
        setText(R.id.tv_sports_time,"00:00");
    }

    public void setTarget(int type,int num){
        this.type = type;
        this.num = num;
        if(num == 0){
            tvSetGoal.setText(getString(R.string.app_set_goal));
        }else {
            tvSetGoal.setText(SportsStatusBarViewUtils.getInstance().targetType(type,num));
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if(isFirst){
            isFirst = false;
            getVersion();
        }
        UserBean myInfo = DataManager.Companion.getInstance().getMyInfo();
        if(myInfo != null){
            tvUserName.setText(getString(R.string.app_main_user_name,myInfo.getNickname()));
            BaseUtils.StaticParams.loadImage(getContext(), R.drawable.app_not_login, myInfo.getHeadimg(),ivUserHead);
        }else {
            tvUserName.setText(getString(R.string.app_main_user_name,"游客"));
            ivUserHead.setImageResource( R.drawable.app_not_login);
//            BaseUtils.StaticParams.loadImage(getContext(), R.drawable.app_not_login, myInfo.getHeadimg(),ivUserHead);
        }

        ((ApplicationPresenter) getPresenter()).getApkList();//获取应用列表
        if(DataManager.Companion.getInstance().getMyInfo() != null){
            ((ApplicationPresenter) getPresenter()).getSportInfo();
        }
        ShowSpeedViewUtils.getInstance().goneLayout();
        SportsStatusBarViewUtils.getInstance().isMain(true);
        setDeviceImg();
        clMain.setBackgroundResource(ThemeUtils.getInstance().getMainTheme());
    }

    @Override
    public void onStop() {
        super.onStop();
        isFirst = true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){

            case R.id.cl_user_login:
                UserBean myInfo = DataManager.Companion.getInstance().getMyInfo();
                if(myInfo != null){
                    openActivity(UserProfileActivity.class);
                }else {
                    openActivity(LoginActivity.class);
                }
                break;
            case R.id.tv_set_goal:
                SetTargetViewUtils.getInstance().initView(getContext());
                break;
            case R.id.cv_programs:
                Bundle bundle = new Bundle();
                bundle.putInt(Constants.BUNDLE_EXTRA, 1);
                openActivity(ProceduralTrainingActivity.class,bundle);
                break;
            case R.id.cv_immersive:
                bundle = new Bundle();
                bundle.putInt(Constants.BUNDLE_EXTRA, 4);
                openActivity(VideoActivity.class, bundle);
                break;
            case R.id.cv_video_course:
                bundle = new Bundle();
                bundle.putInt(Constants.BUNDLE_EXTRA, 1);
                openActivity(VideoActivity.class, bundle);
                break;
            case R.id.cv_audio_course:
                ToastUtils.showShort(getString(R.string.app_toast_hint_2));
                break;
            case R.id.cv_app:
                openActivity(ApplicationActivity.class);
                break;
            case R.id.cl_sport_info:
                bundle = new Bundle();
                bundle.putInt(Constants.BUNDLE_EXTRA,type);
                bundle.putInt(Constants.BUNDLE_EXTRA_2,num);
                openActivity(FreeMovementNewActivity.class,bundle);
                break;

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceive(ApplicationBean bean) {
        appAdapter.notifyDataSetChanged();
        if (bean.getDownloadStatus() == 2 && bean.getInstallStatus() == 0) {  //下载完成了
            bean.setInstallStatus(1);
            installApk(bean.getDownloadFile());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceive(HashMap<String, Object> map) {
        if (map == null) {
            return;
        }
        if (map.containsKey(EventBusEvent.START_RUN)) {
            clSportInfo.setVisibility(View.VISIBLE);
            ArrayList<Integer> target = SportsStatusBarViewUtils.getInstance().getTarget();
            type = Integer.valueOf(target.get(0));
            num = Integer.valueOf(target.get(1));
//            if(type == 0){
//                tvSportsCenter.setText(getString(R.string.app_free_training));
//            }else {
//                tvSportsCenter.setText(SportsStatusBarViewUtils.getInstance().targetType(type, num));
//
//            }
        }else if ( map.containsKey(EventBusEvent.PAUSE_RUN)||map.containsKey(EventBusEvent.STOP_RUN)){
            clSportInfo.setVisibility(View.GONE);
//            tvSportsCenter.setText(getString(R.string.app_sports_center));

        }else if (map.containsKey(EventBusEvent.DEVICE_DATA)) {
            System.out.println("BluetoothOrder -------------> ddddddddddddddddddddddd  CurrentInfo : "+ GsonUtils.toJson((SerialPortManager.CurrentInfo) map.get(EventBusEvent.DEVICE_DATA)));
            SerialPortManager.CurrentInfo currentInfo = (SerialPortManager.CurrentInfo) map.get(EventBusEvent.DEVICE_DATA);
            resetInfo(currentInfo);
        }else if(map.containsKey(EventBusEvent.EQUIPMENT_STATE)){//设备状态
//            SerialPortManager.CurrentInfo currentInfo = (SerialPortManager.CurrentInfo) map.get(EventBusEvent.EQUIPMENT_STATE);
            SerialPortManager.CurrentInfo currentInfo = MotionDataUtils.getInstance().getCurrentInfo();
            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  8888");
            resetInfo(currentInfo);
        }else if(map.containsKey(EventBusEvent.SET_TARGET)){
            ArrayList<String> o = (ArrayList<String>) map.get(EventBusEvent.SET_TARGET);
            type = Integer.valueOf(o.get(0));
            num = Integer.valueOf(o.get(1));
            setTarget(type,num);
        }else if(map.containsKey(EventBusEvent.LOGIN_SUCCESS)){
            UserBean myInfo = DataManager.Companion.getInstance().getMyInfo();
            if(myInfo != null){
                tvUserName.setText(getString(R.string.app_main_user_name,myInfo.getNickname()));
                BaseUtils.StaticParams.loadImage(getContext(), R.drawable.app_not_login, myInfo.getHeadimg(),ivUserHead);
            }

        }else if(map.containsKey(EventBusEvent.REFRESH_FRAG)){
            setDeviceImg();
            SportsStatusBarViewUtils.getInstance().initSlop();
        }else if(map.containsKey(EventBusEvent.KILL_ACTIVITY)){
            clSportInfo.setVisibility(View.GONE);
        }
    }

    public void resetInfo(SerialPortManager.CurrentInfo info) {

//        if(DeviceTypeUtils.connectDeviceType() == 0){
//            if(BluetoothOrder.mCurrentDeviceType.equals(DeviceTypeUtils.TREADMILL)
//                    ||BluetoothOrder.mCurrentDeviceType.equals(DeviceTypeUtils.SPINNING) ){
//                setText(R.id.tvSlope, String.valueOf(info.slop));
//                setText(R.id.tvSpeed, Utils.getNewFloat(info.speed*0.01f));
//            }else if (BluetoothOrder.mCurrentDeviceType.equals(DeviceTypeUtils.ROWING_MACHINE)){
//                setText(R.id.tvSlope, String.valueOf(info.slop));
//                String text;
//                if (info.speed == 0) {
//                    text = "00:00";
//                } else {
//                    int time = (int) (1800 / (info.speed * 0.01) + 0.5);  //计算好了配速   //((info.time == 0 || info.distance < 10) ? 0 : (int) (500 / (info.distance * 1.0f / info.time) + 0.5f));//计算500需要多少秒
//                    int hour = time / 3600;
//                    int minute = (time / 60) % 60;
//                    int second = time % 60;
//                    if (hour > 0) {
//                        text = BaseUtils.StaticParams.getNewText(hour) + ":"
//                                + BaseUtils.StaticParams.getNewText(minute) + ":"
//                                + BaseUtils.StaticParams.getNewText(second);
//                    } else {
//                        text = BaseUtils.StaticParams.getNewText(minute) + ":"
//                                + BaseUtils.StaticParams.getNewText(second);
//                    }
//                }
//                setText(R.id.tvSpeed, text);
//            }
//        }else {
//            if (SerialPortManager.mCurrentDeviceType == DeviceType.RUNNING_MACHINE) {
//                setText(R.id.tvSlope, String.valueOf(info.slop));
//                setText(R.id.tvSpeed, Utils.getNewFloat(info.speed / 10f));
//            } else if (SerialPortManager.mCurrentDeviceType == DeviceType.CAR_WATCH) {
//                setText(R.id.tvSlope, String.valueOf(info.resistance));
//                String text;
//                if (info.speed == 0) {
//                    text = "00:00";
//                } else {
//                    int time = (int) (1800 / (info.speed * 0.01) + 0.5);  //计算好了配速   //((info.time == 0 || info.distance < 10) ? 0 : (int) (500 / (info.distance * 1.0f / info.time) + 0.5f));//计算500需要多少秒
//                    int hour = time / 3600;
//                    int minute = (time / 60) % 60;
//                    int second = time % 60;
//                    if (hour > 0) {
//                        text = BaseUtils.StaticParams.getNewText(hour) + ":"
//                                + BaseUtils.StaticParams.getNewText(minute) + ":"
//                                + BaseUtils.StaticParams.getNewText(second);
//                    } else {
//                        text = BaseUtils.StaticParams.getNewText(minute) + ":"
//                                + BaseUtils.StaticParams.getNewText(second);
//                    }
//                }
//                setText(R.id.tvSpeed, text);
//            }
//
//        }

        float kcal = info.kcal /10f;
        int hour = info.time / 3600;
        int minute = (info.time / 60) % 60;
        int second = info.time % 60;
        if (hour > 0) {
            setInfo(Utils.getNewFloat(kcal),Utils.getNewFloat2(info.distance / 1000f),
                    BaseUtils.StaticParams.getNewText(hour) + ":"
                            + BaseUtils.StaticParams.getNewText(minute) + ":"
                            + BaseUtils.StaticParams.getNewText(second));
        } else {
            setInfo(Utils.getNewFloat(kcal ),Utils.getNewFloat2(info.distance / 1000f),
                    BaseUtils.StaticParams.getNewText(minute) + ":"
                            + BaseUtils.StaticParams.getNewText(second));
        }

    }


    public void getVersionSuccess(@Nullable VersionBean bean) {
        if(bean != null){
            if(DataManager.Companion.getInstance().getIsAutoUpdate()){
                if(EquipmentInfoUtils.getInstance().getVersionCode(getContext()) < bean.getNew_version()){
                    HintPopupWindow hintPopupWindow = new HintPopupWindow(getContext(), bean);
                    hintPopupWindow.show(getActivity());
                }
            }
        }
    }

    public void getVersion() {
        HttpMethods.Companion.getInstance().checkVer(BuildConfig.VERSION_CODE, 6,
                new HttpObserver(this, new HttpListener<VersionBean>() {
                    @Override
                    public void onSuccess(@Nullable VersionBean bean) {

                        getVersionSuccess(bean);
                    }

                    @Override
                    public void dataError(@Nullable int code, @Nullable String msg) {
                        System.out.println("ddddddddddddddddddddddd   getVersion 111");
                        showErrorDialog(code, msg);
                    }

                    @Override
                    public void connectError(@Nullable Throwable e) {
                        System.out.println("ddddddddddddddddddddddd   getVersion 444");
                        showErrorDialog(-1, "");
                    }
                }, getCompositeDisposable()));
    }

    ArrayList<ApplicationBean> datas = new ArrayList<>();
    @Override
    public void getApkListSuccess(ArrayList<ApplicationBean> list) {
        RunningAppUtils.getInstance().setApplicationBeanList(list);
        datas.clear();
        int num = 0;
        if(list != null && list.size()>0){
            if(list.size() >= 5){
                num = 5;
            }else {
                num = list.size();
            }
        }
        for(int i = 0; i<num;i++){
//            ImageLoadUtils.getInstance(getContext()).setImageUtlRadius(ivs.get(i),list.get(i).getIcon(),0,4);
//            if(i<ivMores.size()){
//                ImageLoadUtils.getInstance(getContext()).setImageUtlRadius(ivMores.get(i),list.get(i).getIcon(),0,4);
//            }
//            setText(tvs.get(i),list.get(i).getAppname());
            datas.add(list.get(i));
        }
//
//        setText(tvs.get(5),getString(R.string.app_application_more));
        datas.add(new ApplicationBean());
        ArrayList<ApplicationBean> list1 = OkHttpManager.Companion.getInstance().getMDownLoadingApplication();
        if (!list1.isEmpty()) {
            for (ApplicationBean bean1 : list1) {
                for (int i = 0; i < list.size(); ) {
                    if (bean1.getAppid().equals(list.get(i).getAppid())) {  //如果检测到有正在下载的apk，则需要替换一下，方便更新下载UI
                        list.remove(i);
                        list.add(i, bean1);
                        break;
                    }
                    ++i;
                }
            }
        }
        PackageManager packageManager = getContext().getPackageManager();
        // 获取已安装的app信息
        List<PackageInfo> pkgInfos = packageManager.getInstalledPackages(0);
        if (pkgInfos != null) {
            for (ApplicationBean bean : datas) {
                for (PackageInfo info : pkgInfos) {
                    //  Log.e("aaaaaaaaaa", info.packageName+", "+info.applicationInfo.loadLabel(packageManager).toString());
                    if (bean.getAppid().equals(info.packageName)) {
                        bean.setInstallStatus(2);
                        break;
                    }
                }
            }
        }
        SportsStatusBarViewUtils.getInstance().initAppList(list);
        ApkListViewUtils.getInstance().initAppList(getContext().getApplicationContext(),list);
        System.out.println("ddddddddddddddddddddddd  datas : "+datas.size());
//        RunningAppUtils.getInstance().setHomeApplicationBeanList(datas);
        DataManager.Companion.getInstance().saveHomeApk(datas);
//        initApplication(mRecyclerView,datas);
        for (int i=0;i<imageViewList.size();i++){
            ImageLoadUtils.getInstance(getContext()).setImageUtlRadius(imageViewList.get(i),datas.get(i).getIcon(),0,4);
        }
    }

    @Override
    public void getSportInfoSuccess(SportInfoBean bean) {
        setText(R.id.tvTotalTime, String.valueOf(bean.getAlltime() / 60));
        setText(R.id.tvDistance, bean.getDistance());
        setText(R.id.tvKcal, bean.getKcal());

    }

    @Override
    public DownloadAdapter getDownloadAdapter() {
        return null;
    }

    @Override
    public void installOver(String packageName) {

    }

    @Override
    public void refreshVersion(String packageName) {

    }

    @Override
    public Context getAppContext() {
        return getContext();
    }

    /**
     * 安装apk（非静默安装）
     * @param apkFile
     */
    private void installApk(File apkFile) {

        boolean result = false;
        BufferedReader es = null;
        DataOutputStream os = null;

        try {
            Process process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());

            String command = "pm install -r " + apkFile.getAbsolutePath() + "\n";
            os.write(command.getBytes(Charset.forName("utf-8")));
            os.flush();
            os.writeBytes("exit\n");
            os.flush();

            process.waitFor();
            es = new BufferedReader(new InputStreamReader(process.getErrorStream()));

            String line;
            StringBuilder builder = new StringBuilder();
            while ((line = es.readLine()) != null) {
                builder.append(line);
            }
            Log.d(TAG, "install msg is " + builder.toString());

        /* Installation is considered a Failure if the result contains
            the Failure character, or a success if it is not.
             */
            if (!builder.toString().contains("Failure")) {
                result = true;
            }
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
            try {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    Uri apkUri = FileProvider.getUriForFile(getContext(), AppUtils.getAppPackageName() + ".fileprovider", apkFile);
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                } else {
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    Uri uri = Uri.fromFile(apkFile);
                    intent.setDataAndType(uri, "application/vnd.android.package-archive");
                }
                startActivity(intent);
            } catch (Exception e1) {
            }
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (es != null) {
                    es.close();
                }
            } catch (IOException e) {
                Log.e(TAG, e.getMessage(), e);
            }
        }
    }

}
